<?php

class Kd_Web_History{

    private $_session = NULL;
    private $_sessionKey = '__history';

    public function __construct(){
        $this->_session = Kd_Web::getSession();
        if(!$this->_session->has($this->_sessionKey)){
        	$this->_session->set($this->_sessionKey, array());
        }
    }

    public function get($matchUrl){
        $history = $this->_session->get($this->_sessionKey);
        for($i = count($history) - 1; $i >= 0; $i--){
        	if(Kd_Util_String::startsWith($history[$i], $matchUrl)){
        		return $history[$i];
        	}
        }

        return $matchUrl;
    }

    public function record($url = NULL){
    	if(is_null($url)){
    		$url = $_SERVER['REQUEST_URI'];
    	}
        $history = $this->_session->get($this->_sessionKey, array());
        if (empty($history)){
            $history = array();
        }
        
        $history[] = $url;
        if(count($history) > 10){
            array_shift($history);
        }
        $this->_session->set($this->_sessionKey, $history);
        return $this;
    }

    public function clear(){
        $this->_session->set($this->_sessionKey, array());
    }

}